package me.firstapp.repository.bbs.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import me.firstapp.common.utils.Page;
import me.firstapp.module.bbs.SystemNotification;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.bbs.SystemNotificationRepository;

@Repository
public class SystemNotificationRepositoryImpl extends EntityRepositoryImpl<SystemNotification>
		implements SystemNotificationRepository {

	@Override
	public Long findMemberUnReadSystemNotificationCounts(Long memberId, Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder("SELECT COUNT(bean.id) FROM SystemNotification bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);
		
		sql.append(" AND bean.isRead=:isRead ");
		parameters.put("isRead", 0);

		sql.append(" AND bean.toMember.id=:memberId ");
		parameters.put("memberId", memberId);
		List<Long> countList = super.query(Long.class, sql.toString(), parameters);

		return countList.isEmpty() ? 0 : countList.get(0);
	}

	@Override
	public Page<SystemNotification> findMemberSystemNotificationPage(Integer pageNo, Integer pageSize, Long memberId,
			Integer isRead, Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM SystemNotification bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);
		
		sql.append(" AND bean.toMember.id=:memberId ");
		parameters.put("memberId", memberId);
		if (isRead != null) {
			sql.append(" AND bean.isRead=:isRead ");
			parameters.put("isRead", isRead);
		}
		return super.queryForPage(SystemNotification.class, sql.toString(), parameters, pageNo, pageSize);
	}

	@Override
	protected Class<SystemNotification> getPersistentClass() {
		return SystemNotification.class;
	}

	@Override
	public List<SystemNotification> findUnReadSystemNotificationListByMemberId(Long memberId, Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM SystemNotification bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);
		
		sql.append(" AND bean.isRead=:isRead ");
		parameters.put("isRead", 0);

		sql.append(" AND bean.toMember.id=:memberId ");
		parameters.put("memberId", memberId);

		return super.query(SystemNotification.class, sql.toString(), parameters);
	}

}
